﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using uPLibrary.Networking.M2Mqtt;
using System.Net;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Threading;
using System.ComponentModel;
using System.Windows.Threading;

namespace LindeRmtDigDemo
{
    /// <summary>
    /// wWorkWindow.xaml 的交互逻辑
    /// </summary>
    public partial class wWorkWindow : Window
    {
        public class MqttDev
        {
            public MqttDev()
            { 
            
            }
            private string _mqtthost;
            public string Mqtthost
            {
                get { return _mqtthost; }
                set { _mqtthost = value; }
            }
            private int _mqttport;
            public int Mqttport
            {
                get { return _mqttport; }
                set { _mqttport = value; }
            }
            private string _mqttsubcrbietopic;
            public string Mqttsubcribetopic
            {
                get { return _mqttsubcrbietopic; }
                set { _mqttsubcrbietopic = value; }
            }
            private string _mqttpublictopic;
            public string Mqttpublictopic
            {
                get { return _mqttpublictopic; }
                set { _mqttpublictopic = value; }
            }
              
        }
        MqttDev MqttConfigInfo = new MqttDev(); //初始化全局MQTT参数对象
        MqttClient client;                      //定义MQTT客户端对象
        UserStatusBar Status = new UserStatusBar();
        MqttDataTransFlag MqttDataTransFlag1 = new MqttDataTransFlag();
        
        public wWorkWindow()
        {
            InitializeComponent();
            OpenFileDialog SettingFilePathFd = new OpenFileDialog();           
            string SettingFilePath = "./mqttconfig.ini";
            MqttConfigInfo.Mqtthost = OperateConfigFile.GetValue("HostName", SettingFilePath);
            MqttConfigInfo.Mqttport = Convert.ToInt32(OperateConfigFile.GetValue("HostPort", SettingFilePath));
            MqttConfigInfo.Mqttpublictopic = OperateConfigFile.GetValue("PublishTopicName", SettingFilePath);
            MqttConfigInfo.Mqttsubcribetopic = OperateConfigFile.GetValue("SubcribeTopicName", SettingFilePath);
            try
            {
                tbStatusbar.Text = "正在连接服务器";
                MqttClient TestClient = new MqttClient(MqttConfigInfo.Mqtthost, Convert.ToInt32(MqttConfigInfo.Mqttport), false, null, null, MqttSslProtocols.None);
            }
            catch (Exception ex)
            {
                tbStatusbar.Text = "连接失败，请检查网络连接";
                MessageBox.Show("连接失败，请检查网络连接！");
            }
            client = new MqttClient(MqttConfigInfo.Mqtthost, Convert.ToInt32(MqttConfigInfo.Mqttport), false, null, null, MqttSslProtocols.None);
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            if (client.IsConnected == true)
            {
                tbStatusbar.Text = "Server connected Ok!";
            }
            else
            {
                tbStatusbar.Text = "Server connected Fail!";
            }
            client.Subscribe(new string[] { MqttConfigInfo.Mqttsubcribetopic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
            
        }
        void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // 打印订阅的发布端消息
            string temp = e.Message.ToString();
            string str = System.Text.Encoding.ASCII.GetString(e.Message);
            
            this.tbStatusbar.Dispatcher.BeginInvoke(new Action(() =>
            {
                this.tbStatusbar.Text = DateTime.Now.ToString() + " : ====";
                this.tbStatusbar.Text += "Received" + e.Message.Length + " bytes datas from MQTT SERVER:";
                for (int i = 0; i < e.Message.Length; i++)
                {
                    this.tbStatusbar.Text += e.Message[i].ToString();
                    this.tbStatusbar.Text += "-";
                }
                if ((e.Message[2] == 0x03) && (e.Message[3] == 0x5a))
                {
                    uint DiagVersionLBits = Convert.ToUInt16(e.Message[4]);
                    uint DiagVersionHBits = Convert.ToUInt16(e.Message[5]);                   
                    uint DiagVersion = DiagVersionHBits << 8 | DiagVersionLBits;
                    Double DiagVersionCont = Convert.ToDouble(DiagVersion) / 1000;
                    tbDiagVer.Text = DiagVersionCont.ToString("0.000");
                    MqttDataTransFlag1.CmdDiagVerReceived = true;
                    MqttDataTransFlag1.ReceiveTimes++;
                    byte[] PartNum1 = { 0x07, 0x84, 0x02, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x94 };
                    client.Publish(MqttConfigInfo.Mqttpublictopic, PartNum1, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
                    Thread.Sleep(10);
                    client.Publish(MqttConfigInfo.Mqttpublictopic, PartNum1, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
                    this.tbStatusbar.Text = DateTime.Now.ToString() + " : ====";
                    this.tbStatusbar.Text += "Transmit" + PartNum1.Length + " bytes datas to MQTT SERVER:";
                    for (int i = 0; i < PartNum1.Length; i++)
                    {
                        this.tbStatusbar.Text += PartNum1[i].ToString();
                        this.tbStatusbar.Text += "-";
                    }
                    this.tbStatusbar.Text += "=========Waitting for MQTT SERVER response...";
                }
                else if ((e.Message[2] == 0x04) && (e.Message[3] == 0x5a))
                {
                    byte[] TempData = e.Message.Skip(4).Take(3).ToArray();
                    string EcuNameString = System.Text.Encoding.ASCII.GetString(TempData);
                    tbEcuName.Text = EcuNameString;
                    MqttDataTransFlag1.CmdEcuNameReceived = true;
                    MqttDataTransFlag1.ReceiveTimes++;
                }
                else if ((e.Message[2] == 0x10) && (e.Message[3] == 0x0d))
                {
                    byte[] LongMsgBufH = e.Message.Skip(6).Take(4).ToArray();
                    string PartNumberHalfH = System.Text.Encoding.ASCII.GetString(LongMsgBufH);
                    tbPartNumber.Text = PartNumberHalfH;
                    MqttDataTransFlag1.ReceiveTimes++;
                    byte[] PartNum2 = { 0x07, 0x84, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x94 };
                    client.Publish(MqttConfigInfo.Mqttpublictopic, PartNum2, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
                    this.tbStatusbar.Text = DateTime.Now.ToString() + " : ====";
                    this.tbStatusbar.Text += "Transmit" + PartNum2.Length + " bytes datas to MQTT SERVER:";
                    for (int i = 0; i < PartNum2.Length; i++)
                    {
                        this.tbStatusbar.Text += PartNum2[i].ToString();
                        this.tbStatusbar.Text += "-";
                    }
                    this.tbStatusbar.Text += "=========Waitting for MQTT SERVER response...";
                }
                else if (e.Message[2] == 0x21)
                {
                    byte[] LongMsgBufL = e.Message.Skip(3).Take(7).ToArray();
                    string PartNumberHalfL = System.Text.Encoding.ASCII.GetString(LongMsgBufL);
                    tbPartNumber.Text = tbPartNumber.Text + PartNumberHalfL; //"1285" + PartNumberHalfL;
                    MqttDataTransFlag1.CmdPartNumberReceived = true;
                    MqttDataTransFlag1.ReceiveTimes++;
                    byte[] CmdEcuName = { 0x07, 0x84, 0x02, 0x1a, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x94 };
                    client.Publish(MqttConfigInfo.Mqttpublictopic, CmdEcuName, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
                    this.tbStatusbar.Text = DateTime.Now.ToString() + " : ====";
                    this.tbStatusbar.Text += "Transmit" + CmdEcuName.Length + " bytes datas to MQTT SERVER:";
                    for (int i = 0; i < CmdEcuName.Length; i++)
                    {
                        this.tbStatusbar.Text += CmdEcuName[i].ToString();
                        this.tbStatusbar.Text += "-";
                    }
                    this.tbStatusbar.Text += "=========Waitting for MQTT SERVER response...";
                }
            }));         
        }
        public void Changestatusbar(string str)
        {
            tbStatusbar.Text = str;
        }
        private void ClickGetDeviceInfo(object sender, RoutedEventArgs e)
        {
            byte[] CmdDiagVer = { 0x07, 0x84, 0x02, 0x1a, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x94 };
            client.Publish(MqttConfigInfo.Mqttpublictopic, CmdDiagVer, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false);
            this.tbStatusbar.Text = DateTime.Now.ToString() + " : ====";
            this.tbStatusbar.Text += "Transmit" + CmdDiagVer.Length + " bytes datas to MQTT SERVER:";
            for (int i = 0; i < CmdDiagVer.Length; i++)
            {
                this.tbStatusbar.Text += CmdDiagVer[i].ToString();
                this.tbStatusbar.Text += "-";
            }
            this.tbStatusbar.Text += "=========Waitting for MQTT SERVER response...";





 
        }
        public class MqttDataTransFlag
        {
            public MqttDataTransFlag()
            {
                _cmddiagverreceived = false;
                _cmddiagvertransmited = false;
                _cmdecunamereceived = false;
                _cmdecunametransmited = false;
                _cmdpartnumberreceived = false;
                _cmdpartnumbertransmited = false;
                _communicateendflag = false;
                _receivetimes = 0;
            }
            public void MqttMsgStatsRst()
            {
                _cmddiagverreceived = false;
                _cmddiagvertransmited = false;
                _cmdecunamereceived = false;
                _cmdecunametransmited = false;
                _cmdpartnumberreceived = false;
                _cmdpartnumbertransmited = false;
                _communicateendflag = false;
                _receivetimes = 0;
            }
            private bool _cmddiagverreceived;
            public bool CmdDiagVerReceived
            {
                get { return _cmddiagverreceived; }
                set { _cmddiagverreceived = value; }
            }
            private bool _cmddiagvertransmited;
            public bool CmdDiagVerTransmited
            {
                get { return _cmddiagvertransmited; }
                set { _cmddiagvertransmited = value; }
            }
            private bool _cmdecunamereceived;
            public bool CmdEcuNameReceived
            {
                get { return _cmdecunamereceived; }
                set { _cmdecunamereceived = value; }
            }
            private bool _cmdecunametransmited;
            public bool CmdEcuNameTransmited
            {
                get { return _cmdecunametransmited; }
                set { _cmdecunametransmited = value; }
            }
            private bool _cmdpartnumberreceived;
            public bool CmdPartNumberReceived
            {
                get { return _cmdpartnumberreceived; }
                set { _cmdpartnumberreceived = value; }
            }
            private bool _cmdpartnumbertransmited;
            public bool CmdPartNumberTransmited
            {
                get { return _cmdpartnumbertransmited; }
                set { _cmdpartnumbertransmited = value; }
            }
            private int _receivetimes;
            public int ReceiveTimes
            {
                get { return _receivetimes; }
                set { _receivetimes = value; }
            }
            private bool _communicateendflag;
            public bool CommunicateEndFlag
            {
                get { return _communicateendflag; }
                set { _communicateendflag = value; }
            }
        }
        public class UserStatusBar : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private string _userstatuscont;
            public UserStatusBar()
            { 
            
            }
            public string UserStatusCont
            {
                get { return _userstatuscont; }
                set 
                { 
                    _userstatuscont = value;
                    INotifyPropertyChanged("UserStatusCont");
                }
            }

            private void INotifyPropertyChanged(string info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
        }

        private void ClickRtnAndBkn(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}

